package landun.dao.impl;

import landun.dao.BaseDao;
import landun.dao.BizClaimVoucherDao;
import landun.pojo.BizClaimVoucher;
import landun.pojo.Page;
import landun.pojo.SysEmployee;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.*;

/**
 * 报销单
 */
@Repository("bizClaimVoucherDao")
public class BizClaimVoucherDaoImpl extends BaseDao<BizClaimVoucher> implements BizClaimVoucherDao {


    @Autowired
    public BizClaimVoucherDaoImpl(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public void save(BizClaimVoucher bizClaimVoucher) {
        getHibernateTemplate().saveOrUpdate(bizClaimVoucher);
    }

    @Override
    public BizClaimVoucher get(Serializable id) {
        return getHibernateTemplate().get(BizClaimVoucher.class,id);
    }

    @Override
    public void delete(BizClaimVoucher bizClaimVoucher) {

    }

    @Override
    public List<Object[]> findStatusMap() {
        return this.getHibernateTemplate().execute(new HibernateCallback<List<Object[]>>() {
            @Override
            public List<Object[]> doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("select distinct status from BizClaimVoucher").list();
            }
        });
    }

    @Override
    public List<BizClaimVoucher> findClaimVoucher(final String status, final Date stratDate, final Date endDate, final SysEmployee employee, final Page page) {
        return this.getHibernateTemplate().execute(new HibernateCallback<List<BizClaimVoucher>>() {
            @Override
            public List<BizClaimVoucher> doInHibernate(Session session) throws HibernateException, SQLException {
                String hql = " from BizClaimVoucher ";
                List<Object> objects =new ArrayList<>();
                int positionId = employee.getPosition().getId();
                if(positionId==1){//员工
                    hql+=" where creator.sn=? ";
                }else if(positionId==2){//项目经理
                    hql+=" where nextDeal.id=? and  status!='新创建'";
                }else if(positionId==3){//总经理
                    hql+=" where nextDeal.id=? and  status='待审批' ";
                }else if(positionId==4){//财务
                    hql+=" where nextDeal.id=? and  status='已审批' ";
                }
                //增加第一个查询条件
                objects.add(employee.getSn());
                //判断是否需要加查询条件
                if(StringUtils.isNotBlank(status)){
                    hql+=" and status = ? ";
                    objects.add(status);
                }
                if(stratDate!=null){
                    hql+=" and ? <= createTime ";
                    objects.add(stratDate);
                }
                if(endDate!=null){
                    hql+=" and ? > createTime ";
                    Calendar oneDayLater = Calendar.getInstance();
                    oneDayLater.setTime(endDate);
                    oneDayLater.add(Calendar.DAY_OF_MONTH, 1);
                    objects.add(oneDayLater.getTime());
                }
//                if(positionId==2){
//                    hql+=" order by status,createTime desc ";
//                }
                hql+=" ORDER BY DECODE(status,'新创建',1," +
                        "'已提交',2,'待审批',3,'已打回',4,'已审批',5,'已付款',6,'已终止',7),createTime desc" ;
                Query query = session.createQuery(hql);
                for (int i = 0; i <objects.size() ; i++) {
                    query.setParameter(i, objects.get(i));
                }
                return query.setFirstResult((page.getCurrentPageNo()-1)*page.getPageSize()).
                        setMaxResults(page.getPageSize()).list();
            }
        });
    }

    @Override
    public Integer totalCount(final String status, final Date stratDate, final Date endDate, final SysEmployee employee) {
        return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
            @Override
            public Integer doInHibernate(Session session) throws HibernateException, SQLException {
                String hql = "select count(*) from BizClaimVoucher ";
                int positionId = employee.getPosition().getId();
                List<Object> objects =new ArrayList<>();
                if(positionId==1){//员工
                    hql+=" where creator.sn=? ";
                }else if(positionId==2){//项目经理
                    hql+=" where nextDeal.id=? and status!='新创建'";
                }else if(positionId==3){//总经理
                    hql+=" where nextDeal.id=? and  status='待审批' ";
                }else if(positionId==4){//财务
                    hql+=" where nextDeal.id=? and  status='已审批' ";
                }
                //增加第一个查询条件
                objects.add(employee.getSn());
                //判断是否需要加查询条件
                if(StringUtils.isNotBlank(status)){
                    hql+=" and status = ? ";
                    objects.add(status);
                }
                if(stratDate!=null){
                    hql+=" and ? <= createTime ";
                    objects.add(stratDate);
                }
                if(endDate!=null){
                    hql+=" and ? > createTime ";
                    objects.add(endDate);
                }
                Query query = session.createQuery(hql);
                for (int i = 0; i <objects.size() ; i++) {
                    query.setParameter(i, objects.get(i));
                }

                Object o = query.uniqueResult();
                if(o!=null){
                   return  ((Long)o).intValue();
                }
                return 0;
            }
         });
    }


    @Override
    public void updateClaimVoucher(BizClaimVoucher bizClaimVoucher) {
        getHibernateTemplate().save(bizClaimVoucher);
    }

    @Override
    public BizClaimVoucher findVoucherById(final Integer id) {
        return getHibernateTemplate().execute(new HibernateCallback<BizClaimVoucher>() {
            @Override
            public BizClaimVoucher doInHibernate(Session session) throws HibernateException, SQLException {
                return (BizClaimVoucher)session.createQuery("from BizClaimVoucher b left join fetch b.detailList left join fetch b.checkResultList where b.id = ?").setParameter(0,id).uniqueResult();
            }
        });
    }










//项目经理
    @Override
    public List<BizClaimVoucher> managerFindVoucher(final Integer deptId, final Page page) {
        return getHibernateTemplate().execute(new HibernateCallback<List<BizClaimVoucher>>() {
            @Override
            public List<BizClaimVoucher> doInHibernate(Session session) throws HibernateException, SQLException {
                return session.
                        createQuery
                                ("from BizClaimVoucher b where b.status!='新创建' and b.creator.departmentId=?").
                        setParameter(0,deptId).
                        setFirstResult(page.getCurrentPageNo()-1).
                        setMaxResults(page.getPageSize()).list();
            }
        });
    }
//总经理
    @Override
    public List<BizClaimVoucher> generalmanagerFindVoucher(final Integer id, final Page page) {
        return getHibernateTemplate().execute(new HibernateCallback<List<BizClaimVoucher>>() {
            @Override
            public List<BizClaimVoucher> doInHibernate(Session session) throws HibernateException, SQLException {
                return session.
                        createQuery
                                ("from BizClaimVoucher  where nextDeal.sn = ? and status!='新创建' " +
                                        " ORDER BY DECODE(BizClaimVoucher.status,'新创建','1'," +
                                        "'已提交','2','待审批','3','已打回','4','已审批','5','已付款','6','已终止','7')," +
                                        "createTime desc").setParameter(0,id).list();
            }
        });
    }
//财务
    @Override
    public List<BizClaimVoucher> cashierFindVoucher(final Integer id, final Page page) {
        return getHibernateTemplate().execute(new HibernateCallback<List<BizClaimVoucher>>() {
            @Override
            public List<BizClaimVoucher> doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("from BizClaimVoucher where nextDeal.sn = ? and status='已审批' ").
                setParameter(0,id).list();
            }
        });
    }
}
